<?php
/**
 * @version $Id: view.html.php 427 2012-03-26 10:05:34Z lnmtrung@gmail.com $
 */
defined( '_JEXEC' ) or die( 'Restricted access' );

class WrdViewProfile extends WrdView{
	
	function display($tpl = null) {
		$user  = &JFactory::getUser();
		if(!$user->authorise('wrd.dashboard.profile', 'com_wrd'))
			return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
		
		$this->setModel($this->getModel('profile'), true);
		$fnc = 'display'.ucfirst($this->getLayout());
		if (is_callable(array(&$this, $fnc))){
			$this->$fnc($tpl);
		}else{
			parent::display($tpl);
		}
	}
	
	function displayDefault($tpl = null){
        $mainframe = &JFactory::getApplication();
        $user	= &JFactory::getUser();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		//check Convert point
		$db = JFactory::getDbo();
		$sql = 'SELECT user_id,created_date FROM #__wrd_point WHERE (flagConvert=1)';
		$db->setQuery($sql);
		$rows = $db->loadObjectList();
		
		$document = & JFactory::getDocument();	
		$document->setTitle(JText::_('Profile Manager'));
        
		JToolBarHelper::title(JText::_('Profile Manager'),'profile.png');
		if($user->authorise('wrd.profile.expiredpoint', 'com_wrd'))
			JToolBarHelper::custom('check_expired_point','expired','expired','Expired Point',false);
		
		if(count($rows)):
			JToolBarHelper::custom('convertToSummaryPoint','convert','converttosummarypoint','Convert To Summary Point',false);
		endif;

		if($user->authorise('wrd.profile.birthday', 'com_wrd'))
			JToolBarHelper::custom('send_mail_birth','messaging','messaging','Birthday');

		if($user->authorise('wrd.profile.addnew', 'com_wrd'))
			JToolBarHelper::addNew();
		if($user->authorise('wrd.profile.delete', 'com_wrd'))
			JToolBarHelper::deleteList();
		if($user->authorise('wrd.dashboard.admin', 'com_wrd'))
			JToolBarHelper::preferences('com_wrd','profile', '600');
		$this->assignRef('user', $user);

		WrdHelper::addSubMenu($view);
		$this->sidebar = JHtmlSidebar::render();
		
		
		$view = JRequest::getCmd('view');
		$filter_order     		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_item','filter_order','id' );
		$filter_order_Dir 		= $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir','filter_order_Dir', '' );
		$lists['order'] 		= $filter_order;
		$lists['order_Dir'] 	= $filter_order_Dir;
		$items					= & $this->get( 'Data');
		//echo '<pre>';print_r($items);
		$total					= & $this->get( 'Total');
		$pagination 			= & $this->get( 'Pagination' );
		$search 				= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string' );
		$srch_type 				= JRequest::get('post');
		$mem_id 				= $srch_type['mem_id'] ;
		$u_name 				= $srch_type['u_name'] ;
		$u_fone 				= $srch_type['u_fone'] ;
		$u_company 				= $srch_type['u_company'] ;

		$profilefillter 		= $mainframe->getUserStateFromRequest( $context.$view.'profilefillter','profilefillter',0,'int' );
		$searchfillter 			= $mainframe->getUserStateFromRequest( $context.$view.'searchFillter','searchfillter');
		$datefillter 			= $mainframe->getUserStateFromRequest( $context.$view.'dateFillter','datefillter');
		
		$filter_pick_up_outlet 	= $mainframe->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','string' );
		
		$search 				= JString::strtolower( $search );

		$lists['search'] 				= $search;
		$lists['profilefillter'] 		= JHTML::_('wrd.profilefillter',$profilefillter,'onchange="this.form.submit()"');
		$lists['searchFillter'] 		= JHTML::_('wrd.searchFillter',$searchfillter);
		$lists['datefillter'] 			= JHTML::_('wrd.dateFillter',$datefillter);
		
		$orderfield 					= $mainframe->getUserStateFromRequest( $context.$view.'order_field','order_field');
		$lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsP','pick_up_at',$filter_pick_up_outlet,'onchange="this.form.submit()"','pick_up_at','','and pid != 00' );
	    
		$filter_byfrom = $mainframe->getUserStateFromRequest( $context.$view.'byfrom','byfrom','','int' );
		$filter_bmfrom = $mainframe->getUserStateFromRequest( $context.$view.'bmfrom','bmfrom','','int' );
		$filter_bdfrom = $mainframe->getUserStateFromRequest( $context.$view.'bdfrom','bdfrom','','int' );
		$filter_byto   = $mainframe->getUserStateFromRequest( $context.$view.'byto','byto','','int' );
		$filter_bmto   = $mainframe->getUserStateFromRequest( $context.$view.'bmto','bmto','','int' );
		$filter_bdto   = $mainframe->getUserStateFromRequest( $context.$view.'bdto','bdto','','int' );
		
		$lists['byfrom'] = JHTML::_('wrd.genarateListBox','byfrom',$filter_byfrom,'','byfrom',1900,date('Y'),1900) ;
	
		$lists['bmfrom'] = JHTML::_('wrd.genarateListBox','bmfrom',$filter_bmfrom,'','bmfrom',1, 12,1) ;
		$lists['bdfrom'] = JHTML::_('wrd.genarateListBox','bdfrom',$filter_bdfrom,'','bdfrom',1, 31,1) ;
		$lists['byto']   = JHTML::_('wrd.genarateListBox','byto',$filter_byto,'','byto',1900,date('Y'),date('Y')) ;
		$lists['bmto'] 	 = JHTML::_('wrd.genarateListBox','bmto',$filter_bmto,'','bmto',1, 12,12) ;
		$lists['bdto'] 	 = JHTML::_('wrd.genarateListBox','bdto',$filter_bdto,'','bdto',1, 31,31) ;
		
		$filter_cyfrom = $mainframe->getUserStateFromRequest( $context.$view.'cyfrom','cyfrom','','int' );
		$filter_cmfrom = $mainframe->getUserStateFromRequest( $context.$view.'cmfrom','cmfrom','','int' );
		$filter_cdfrom = $mainframe->getUserStateFromRequest( $context.$view.'cdfrom','cdfrom','','int' );
		$filter_cyto   = $mainframe->getUserStateFromRequest( $context.$view.'cyto','cyto','','int' );
		$filter_cmto   = $mainframe->getUserStateFromRequest( $context.$view.'cmto','cmto','','int' );
		$filter_cdto   = $mainframe->getUserStateFromRequest( $context.$view.'cdto','cdto','','int' );

		$filter_pyfrom = $mainframe->getUserStateFromRequest( $context.$view.'pyfrom','pyfrom','','int' );
		$filter_pmfrom = $mainframe->getUserStateFromRequest( $context.$view.'pmfrom','pmfrom','','int' );
		$filter_pdfrom = $mainframe->getUserStateFromRequest( $context.$view.'pdfrom','pdfrom','','int' );
		$filter_pyto   = $mainframe->getUserStateFromRequest( $context.$view.'pyto','pyto','','int' );
		$filter_pmto   = $mainframe->getUserStateFromRequest( $context.$view.'pmto','pmto','','int' );
		$filter_pdto   = $mainframe->getUserStateFromRequest( $context.$view.'pdto','pdto','','int' );

	    $this->assignRef('search',		$search);
	    $this->assignRef('u_name',		$u_name);
	    $this->assignRef('mem_id',		$mem_id);
	    $this->assignRef('u_fone',		$u_fone);
	    $this->assignRef('u_company',	$u_company);
	    $this->assignRef('lists',		$lists);
	  	$this->assignRef('items',		$items);
	  	$this->assignRef('user',		$user);
	    $this->assignRef('pagination',	$pagination);
	    
	    parent::display($tpl);
  	}
	
	function displayForm($tpl = null){ 
		
		$mainframe = &JFactory::getApplication();
		$configField = WrdHelper::getConfigFieldRegistration();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$user = JFactory::getUser();
		$cid = JRequest::getInt('id');
		$model	=& $this->getModel();
		$total					= & $this->get( 'Total');
		
		WrdHelper::addSubMenu($view);
		$this->sidebar = JHtmlSidebar::render();
		
		$detail = array();
  		if($cid != 0){
			$detail	=& $model->getItem($cid);
			if(!empty($detail->modify_by)) $modify = & $model->getModifyBy($detail->modify_by);
			else $modify = & $model->getModifyBy($detail->created_id);
			$filesalbum = WrdHelper::getFiles($cid,$user->id,'profile');
		}
		else{
			$filesalbum = WrdHelper::getFiles($cid,$user->id,'profile');
		}  
		//var_dump($cid);
		$lists = array();
		$lists['published'] 		= JHTML::_('wrd.published','published',$detail->published,'',0);
		$lists['prefix'] 			= JHTML::_('wrd.prefix',$detail->prefix,'',1);
		$lists['job_prefix'] 		= JHTML::_('wrd.job_prefix',$detail->job_prefix,'',1);
		$js_job 					= "onchange=\"showOther( 'job','fl_o_job');\"";
        $js_job                     = "";
		$lists['job'] 				= JHTML::_('wrd.listJob','job',$detail->job ,$js_job,'job','e');
		
		$lists['industry'] 			= JHTML::_('wrd.listIndustry','industry',($detail->industry > 0 ? $detail->industry : 0) ,'',0);
		$js_department 				= "onchange=\"showOther( 'department','fl_o_department');\"";
		$lists['department'] 		= JHTML::_('wrd.listDepartment','department',$detail->department ,$js_department,0);
		$lists['gender'] 		    = JHTML::_('wrd.gender',$detail->gender,'gender');     
		
		$js_c_education 			= "onchange=\"showOther( 'education','fl_o_education');\"";
		$lists['education'] 		= JHTML::_('wrd.listEducation','education',$detail->education ,$js_c_education,'',5);
		
		$o_club = unserialize($detail->o_club);
		$lists['o_club'] 			= JHTML::_('wrd.listOClub','o_club[]',$o_club ,'','',5);
		
		$lists['income'] 			= JHTML::_('wrd.listIncome','income',$detail->income ,'',0);
		$lists['status'] 			= JHTML::_('wrd.listStatus','status',$detail->status ,'',0);
		$lists['referer'] 			= JHTML::_('wrd.listUser','referer',$detail->referer,'','profile',0);
        $lists['lang_prefer'] 		= JHTML::_('wrd.lprefer','lprefer',(($cid == 0) ? 1 : $detail->lprefer),'','lprefer width305',0);
		$lists['nationality'] 		= JHTML::_('wrd.listCountry','nationality',(($cid == 0) ? 249 : $detail->nationality),'','country',1 );
		
		$user_birth = explode('-', $detail->dob) ;
        /******* Check if current year is duplicate with user birth -> reset *******/
        if(date('Y', time()) == $user_birth[0] )
        {
            $user_birth[0] = "";
            $user_birth[1] = "";
            $user_birth[2] = "";
        }
        
		$lists['day_birth'] 		= JHTML::_('wrd.listDateOfMonth','day_birth',$user_birth[2],'','select40');
		$lists['month_birth'] 		= JHTML::_('wrd.listMonthOfYear','month_birth',$user_birth[1],'','select40');
		$lists['year_birth'] 		= JHTML::_('wrd.listYear','year_birth',$user_birth[0]);
	
		$filter_country_id 			= $mainframe->getUserStateFromRequest($context.$view.'country','country',$detail->country,'int');
		$javascript_country_to_city = "onchange=\"changeCity( 'city', sectioncountrys,document.adminForm.country.options[document.adminForm.country.selectedIndex].value , 0, 0);\"";
		
		$filter_city_id 			= $mainframe->getUserStateFromRequest($context.$view.'city','city',$detail->city,'int');
		$javascript_city_to_distric = " style=\"width:250px;\" onchange=\"changeDistric( 'distric', sectioncitys,document.adminForm.city.options[document.adminForm.city.selectedIndex].value , 0, 0);\"";
		
		$lists['country'] 			= JHTML::_('wrd.listCountry','country',(($cid == 0) ? 249 : $detail->country),$javascript_country_to_city,'country',0 );
		$lists['city'] 				= JHTML::_('wrd.listCity','city',($filter_city_id > 0 ? $filter_city_id : 0),$javascript_city_to_distric,'city',0);
		
		$lists['distric'] 			= JHTML::_('wrd.listDistric','distric',!empty($detail->distric) ? $detail->distric:0,'distric');
		
		$lists['countryToCity'] 	= JHTML::_('wrd.countryToCity');
		$lists['cityToDistric'] 	= JHTML::_('wrd.cityToDistric');
		
		$filter_company_country_id 			= $mainframe->getUserStateFromRequest($context.$view.'c_country','c_country',$detail->c_country,'int');
		$javascript_company_country_to_city = "onchange=\"changeCity( 'c_city', sectioncountrys,document.adminForm.c_country.options[document.adminForm.c_country.selectedIndex].value , 0, 0);\"";
		
		$filter_company_city_id 			= $mainframe->getUserStateFromRequest($context.$view.'c_city','c_city',$detail->c_city,'int');
		$javascript_company_city_to_distric = "onchange=\"changeDistric( 'c_distric', sectioncitys,document.adminForm.c_city.options[document.adminForm.c_city.selectedIndex].value , 0, 0);\"";
		
		$lists['company_country'] 			= JHTML::_('wrd.listCountry','c_country',(($cid == 0) ? 249 : $detail->c_country),$javascript_company_country_to_city,'c_country',1 );
		$lists['company_city'] 				= JHTML::_('wrd.listCity','c_city',$filter_company_city_id,$javascript_company_city_to_distric,'c_city',1 );
		$lists['company_distric'] 			= JHTML::_('wrd.listDistric','c_distric',!empty($detail->c_distric)?$detail->c_distric:0,'c_distric' );
		
		$lists['company_countryToCity'] 	= JHTML::_('wrd.countryToCity');
		$lists['company_cityToDistric'] 	= JHTML::_('wrd.cityToDistric');
		
		//$lists['o_source'] = JHTML::_('wrd.listSources','o_source',$detail->o_source,'','o_source','tr',1, ' ORDER BY id DESC, `name` ASC ');
        $lists['pick_up_oulet'] = JHTML::_('wrd.listOutletsP','pick_up_at',$detail->pick_up_at,'','pick_up_at','', $condition = 'and pid != 00 ORDER BY `name` ASC, `cid` DESC '); 
		
		if(empty($detail->mem_card_outlet)){
			if(!empty($detail->pick_up_at)){
				$detail->mem_card_outlet = $detail->pick_up_at ;
			}
		}
		
        $lists['non_mem_card_outlet'] = JHTML::_('wrd.listOutletsP','non_mem_card_outlet',$detail->non_pick_up_at,'','non_mem_card_outlet','', $condition = 'and pid != 00 ORDER BY `name` ASC, `cid` DESC ');
		$lists['mem_card_outlet'] = JHTML::_('wrd.listOutletsP','mem_card_outlet',$detail->mem_card_outlet,'','mem_card_outlet','', $condition = 'and pid != 00 ORDER BY `name` ASC, `cid` DESC ');
		
		$bations = unserialize($detail->bation);
		$lists['bation'] 		= JHTML::_('wrd.listBation','bation[]',$bations,'','',5);
				
		$text = ($detail->id < 1) ? JText::_( 'NEW' ) : JText::_( 'EDIT' );
		
		$q = "SELECT sum(point) as point FROM #__wrd_point `t` WHERE `t`.user_id = '".$detail->user_id ."' AND `t`.expired = 0 ";
		$db = JFactory::getDbo();
		$db->setQuery($q);
		
		$infotest = $db->loadObject();
		
		$this->assignRef('infotest',$infotest);
		
		//end get point
		
		$this->assignRef('modify',		$modify);
		$this->assignRef('text',		$text);	
		$this->assignRef('data',		$detail);
		$this->assignRef('lists',		$lists);
		
		$this->assignRef('user',		$user);
		$this->assignRef('filesalbum',	$filesalbum);
		$social = unserialize($detail->social);
		$this->assignRef('social',	$social);
		
		$model_hobbies = &JModelLegacy::getInstance('hobbies','WrdModel');		
		
		$all_hobbies = $model_hobbies->getListHobbies();
		$list_hobbies = $model_hobbies->getParentItem();
		$child_hob = array();
		$hobbi_name = array();
		
		foreach($all_hobbies as $parent){
			$child_hob[$parent->id] =  $model_hobbies->getItemChild($parent->id);
			$hobbi_name[$parent->id] =  $model_hobbies->getItemName($parent->id);
		}
		
		$this->assignRef('hobbi_name',	$hobbi_name);
		$this->assignRef('all_hobbies',	$all_hobbies);
		$this->assignRef('list_hobbies',	$list_hobbies);
		$this->assignRef('list_child_hobbies',	$child_hob);
		$u_hobbies = unserialize($detail->hobbies);
		$this->assignRef('u_hobbies',	$u_hobbies);
		$this->assignRef('configField', $configField);
		$complains	= &JModelLegacy::getInstance('complain','WrdModel');
		if($cid != 0){
			$items = $complains->getComplain($cid,'', '',0);
			$this->assignRef('items',		$items);
		} 
		//transaction history
		$total_cost = 0 ;
		
		$transaction = WrdHelper::getTransaction($detail->member_id, '', '');
		
		if(!empty($transaction)){
			foreach ($transaction as $tr){
				$total_cost += $tr->total ;
			}
		}
		$totalSpending = WrdHelper::getTotalTransaction($detail->member_id);
		
		$reedem = $this->getRedemtion($detail->user_id);
		
		$p_details = array() ;
		$total_points_used = 0 ;
		if(count($reedem) > 0){
			foreach ($reedem as $r){
				$p_details[$r->product_id] = $this->getProductDetails($r->product_id) ;
				if($r->approved == 1 || $r->approved == 0){
					$total_points_used += $r->point ;
				}
			}
		}
		$t_outlet = array() ;
		$p_o_u = 0 ;
		if(!empty($detail->user_id)){
		
			$point = $this->getPoint($detail->user_id);
			$u_complains = $this->getComplains($detail->member_id);
			$mservices = $this->getmservices($detail->member_id);
			$total_points = 0 ;	
			foreach ($point as $child_point){
				
				$t_outlet[$child_point->transaction] = $this->getTransactionOutlet($child_point->transaction) ;
				$total_points += $child_point->point ;
			    
            }
			$p_o_u = WrdHelper::getPoints($detail->user_id);
			$p_o_u_e = WrdHelper::getPointsEarn($detail->user_id);
		}
		
		$sql ="SELECT DISTINCT a.vip_number FROM #__wrd_transaction AS a 
			INNER JOIN #__wrd_profile AS b ON a.vip_number = b.member_id 
			WHERE b.p_o_u=0 AND a.vip_number =".$detail->member_id;
		$db->setQuery($sql);
		$rss = $db->loadObjectList();
		
		if(((float)($totalSpending->total) != (float)($detail->total_spend))||((float)($totalSpending->total) != (float)($total_cost))||((float)($total_cost) != (float)($detail->total_spend))):
			JToolBarHelper::custom('uSpend','convert','uspend','Update Spending',false);
		endif;
		//echo count($rss);
		if((intval($infotest->point) != intval($detail->p_o_u))||
			(intval($infotest->point) != intval($p_o_u->point))||
			(intval($detail->p_o_u) != intval($p_o_u->point))||
			(count($rss)>0)):
			JToolBarHelper::custom('uPoint','convert','upoint','Update Point',false);
		endif;
		
		if(JRequest::getVar('pointtmp') == 1){
			JToolBarHelper::custom('uPoint','convert','upoint','Update Point',false);
		}
		JToolBarHelper::title(   JText::_( 'Profile' ).': <small><small>['.$text.']</small></small>','job.png' );
		
		if($user->authorise('wrd.profile.addnew', 'com_wrd'))
			JToolBarHelper::apply();
		if($user->authorise('wrd.profile.addnew', 'com_wrd'))
			JToolBarHelper::save();
		JToolBarHelper::cancel( 'cancel', 'Close' );
		if($user->authorise('wrd.dashboard.admin', 'com_wrd'))
			JToolBarHelper::preferences('com_wrd','profiledetail', '600');
		$lists['numChild'] 	= JHTML::_('wrd.listNumChildren','num_children',$detail->num_children ,'','num_children');
		jimport('joomla.user.helper');
		$g_pass = JUserHelper::genRandomPassword() ;
		
		$this->assignRef('point',			$point);
		$this->assignRef('total_points',	$total_points);
		$this->assignRef('p_details',		$p_details);
		$this->assignRef('t_outlet',		$t_outlet);
		$this->assignRef('reedem',			$reedem);
		$this->assignRef('u_complains',		$u_complains);
		$this->assignRef('mservices',		$mservices);
		$this->assignRef('transaction',		$transaction);
		$this->assignRef('total_cost',		$total_cost);
		$this->assignRef('totalSpending',	$totalSpending);
        
		$model_act_weekend = &JModelLegacy::getInstance('aweekend','WrdModel');
		$list_aweekend = $model_act_weekend->getList();
        $this->assignRef('list_aweekend',	$list_aweekend);
		$u_act_w = unserialize($detail->weekend_action);
		$this->assignRef('u_act_w',	$u_act_w);
        $this->assignRef('lists',	$lists);
        $this->assignRef('g_pass',	$g_pass);
		$p_o_tran = array();
		
		$this->assignRef('p_o_tran',	$p_o_tran);
		$this->assignRef('p_o_u',	$p_o_u);
		$this->assignRef('p_o_u_e',	$p_o_u_e);
		$this->assignRef('total_points_used',	$total_points_used);
		
		$limitstart = JRequest::getInt('start',0);
		$lists_lucky_number = $this->getLuckyNum('',0);
		$total_lucky_number = $this->getLuckyNum('',1);
		$this->assignRef('lists_lucky_number',	$lists_lucky_number);
        $this->assignRef('total_lucky_number',	$total_lucky_number->total_lnum);
        $this->assignRef('limitstart',	$limitstart);
        
		$filter_yfrom = $mainframe->getUserStateFromRequest( $context.$view.'yfrom','yfrom','','int' );
		$filter_mfrom = $mainframe->getUserStateFromRequest( $context.$view.'mfrom','mfrom','','int' );
		$filter_dfrom = $mainframe->getUserStateFromRequest( $context.$view.'dfrom','dfrom','','int' );
		$filter_yto   = $mainframe->getUserStateFromRequest( $context.$view.'yto','yto','','int' );
		$filter_mto   = $mainframe->getUserStateFromRequest( $context.$view.'mto','mto','','int' );
		$filter_dto   = $mainframe->getUserStateFromRequest( $context.$view.'dto','dto','','int' );
		
		$lists['yfrom'] = JHTML::_('wrd.genarateListBox','yfrom',$filter_yfrom,'','yfrom',1980, date('Y'),'Y') ;
		$lists['mfrom'] = JHTML::_('wrd.genarateListBox','mfrom',$filter_mfrom,'','mfrom',1, 12,'M') ;
		$lists['dfrom'] = JHTML::_('wrd.genarateListBox','dfrom',$filter_dfrom,'','dfrom',1, 31,'D') ;
		$lists['yto']   = JHTML::_('wrd.genarateListBox','yto',$filter_yto,'','yto',1980, date('Y'),'Y') ;
		$lists['mto'] 	 = JHTML::_('wrd.genarateListBox','mto',$filter_mto,'','mto',1, 12,'M') ;
		$lists['dto'] 	 = JHTML::_('wrd.genarateListBox','dto',$filter_dto,'','dto',1, 31,'D') ;
		
		$filter_tyfrom = $mainframe->getUserStateFromRequest( $context.$view.'tyfrom','tyfrom','','int' );
		$filter_tmfrom = $mainframe->getUserStateFromRequest( $context.$view.'tmfrom','tmfrom','','int' );
		$filter_tdfrom = $mainframe->getUserStateFromRequest( $context.$view.'tdfrom','tdfrom','','int' );
		$filter_tyto   = $mainframe->getUserStateFromRequest( $context.$view.'tyto','tyto','','int' );
		$filter_tmto   = $mainframe->getUserStateFromRequest( $context.$view.'tmto','tmto','','int' );
		$filter_tdto   = $mainframe->getUserStateFromRequest( $context.$view.'tdto','tdto','','int' );
		
		$lists['tyfrom'] = JHTML::_('wrd.genarateListBox','tyfrom',$filter_tyfrom,'','tyfrom',1980, date('Y'),'Y') ;
		$lists['tmfrom'] = JHTML::_('wrd.genarateListBox','tmfrom',$filter_tmfrom,'','tmfrom',1, 12,'M') ;
		$lists['tdfrom'] = JHTML::_('wrd.genarateListBox','tdfrom',$filter_tdfrom,'','tdfrom',1, 31,'D') ;
		$lists['tyto']   = JHTML::_('wrd.genarateListBox','tyto',$filter_tyto,'','tyto',1980, date('Y'),'Y') ;
		$lists['tmto'] 	 = JHTML::_('wrd.genarateListBox','tmto',$filter_tmto,'','tmto',1, 12,'M') ;
		$lists['tdto'] 	 = JHTML::_('wrd.genarateListBox','tdto',$filter_tdto,'','tdto',1, 31,'D') ;
		
		parent::display($tpl);
	}
	
	function getPoint($id = 0){
		$db = JFactory::getDbo();
		$query = "SELECT `p`.transaction,`p`.point,`p`.redemption_id,`p`.created_date,`p`.des,`p`.type, `p`.expire
				FROM #__wrd_point AS p 
				WHERE `p`.user_id = '".$id."'
				ORDER BY `created_date` DESC	
		";
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs;
	}
	
	function displayPinfo($tpl = null){
		$pid = &JRequest::getCmd('pid', 0);
		$p_details = array() ;
		if($pid != -1){
			$p_details = $this->getProductDetails($pid) ;
		}
		$this->assignRef('p_details',$p_details);
	    parent::display($tpl);
  	}

	function displayFil_redemp($tpl = null){
		$uid = JRequest::getVar('uid') ;
		$yfrom = JRequest::getVar('yfrom') ;
		$mfrom = JRequest::getVar('mfrom') ;
		$dfrom = JRequest::getVar('dfrom') ;
		$yto = JRequest::getVar('yto') ;
		$mto = JRequest::getVar('mto') ;
		$dto = JRequest::getVar('dto') ;
		$reedem = $this->getListRedemtion($uid,$yfrom,$mfrom,$dfrom,$yto,$mto,$dto);
		$p_details = array() ;
		if(count($reedem) > 0){
			foreach ($reedem as $r){
				$p_details[$r->product_id] = $this->getProductDetails($r->product_id) ;
			}
		}
		$this->assignRef('p_details',$p_details);
		$this->assignRef('reedem',	$reedem);
	    parent::display($tpl);
  	}
  	
  	function displayFil_tran($tpl = null){
  		$uid = JRequest::getVar('uid') ;
		$tid = JRequest::getVar('mid') ;
		$tyfrom = JRequest::getVar('tyfrom') ;
		$tmfrom = JRequest::getVar('tmfrom') ;
		$tdfrom = JRequest::getVar('tdfrom') ;
		$tyto = JRequest::getVar('tyto') ;
		$tmto = JRequest::getVar('tmto') ;
		$tdto = JRequest::getVar('tdto') ;
		$ttran = $this->getTransaction($tid,$tyfrom,$tmfrom,$tdfrom,$tyto,$tmto,$tdto,0);
  		if(count($ttran) > 0){
			foreach ($ttran as $tran){
				$p_o_tran[$tran->id] = $this->getPointOfTran($uid, $tran->transaction_id ) ;
			}
		}
		$total_cost = 0 ;
		$ttal_cost = $this->getTransaction($tid,0,0,0,0,0,0,1);
		$total_cost= $ttal_cost->totalcosttran ;
		$total_points_used = $this->getRedemtionTotalCost($uid);
		$p_o_u = WrdHelper::getPoints($uid) ;
		$this->assignRef('ttran',	$ttran);
		$this->assignRef('total_cost',	$total_cost);
		$this->assignRef('p_o_u',	$p_o_u);
		$this->assignRef('p_o_tran',	$p_o_tran);
		$this->assignRef('total_points_used',	$total_points_used);
	    parent::display($tpl);
  	}
  	
	function displaylnum($tpl = null){
		$limitstart = JRequest::getInt('start',0);
		$lists_lucky_number = $this->getLuckyNum('',0,$limitstart);
		$total_lucky_number = $this->getLuckyNum('',1);
		$this->assignRef('lists_lucky_number',	$lists_lucky_number);
        $this->assignRef('total_lucky_number',	$total_lucky_number->total_lnum);
        $this->assignRef('limitstart',	$limitstart);
	    parent::display($tpl);
  	}
  	
	function displayAdd_points($tpl = null){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$user_id = JRequest::getInt('user_id');
		$user = JFactory::getUser($user_id);
		$this->assignRef('user',	$user);
		parent::display($tpl);
	}

    function displayPointlist($tpl = null){
        
		$db = JFactory::getDbo();
        $userId = &JRequest::getCmd('uid', 0);
        $totalPoint = JRequest::getCmd('totalPoint', 0); 
		$productList = strval($_POST['productList']);
        $productList = json_decode($productList);
		$points = 0;
		
        if(!empty($productList))
        {
            $html = '';
            $productIds = '';
            foreach($productList as $item)
            {
                $productIds .= $item->id.',';
            }
            
            $productModels = PointProvider::checkProductQuantity($db, array('ids'=>trim($productIds, ',')));
                        
            if(!empty($productModels)) {
                foreach($productModels as $item) {
                    foreach($productList as $key => $model) {
                        if($item->id == $model->id) {
                            $productList[$key]->status = ($item->quantity - $model->quantity > 0 ? 1 : 0);
                            $productList[$key]->store = $item->quantity;
                            $productList[$key]->product = $item->name;
                            break;
                        }
                    }        
                }
            }
            
            if(!empty($productList)) {
                
                foreach($productList as $item) {
                    if($item->status == 0){
                        $pro = unserialize($item->product);
						$html .= ucfirst($pro['en-GB']).' has only '.$item->store." item(s). Please update this product's quantity!<br />";
                    }
                }
            }
            if($html != "") {
                echo $html; die;
            }
        }
        $currentPointOfUser = 0;
		
        if($userId > 0)
        {
			
            $points = PointProvider::getPointOfUser($db, array('userId'=>$userId));
            if(!empty($points)) {
                foreach($points as $item){
                    $currentPointOfUser += $item->point;
                }
            }
        }
		
		
        if($currentPointOfUser < $totalPoint) {
		
            $html = 'User has only '.number_format($currentPointOfUser, 0, '.', '.').' points. User need '.number_format($totalPoint, 0,'.','.').' points to redeem.';
            echo $html; die;
        }
		
		$p_o_u = WrdHelper::getPoints($userId);
        $this->assignRef('currentPointOfUser', $p_o_u);
        $this->assignRef('points', $points);
        $this->assignRef('totalPoint', $totalPoint);
        parent::display($tpl);
    }

    function displayViewProductDetails($tpl = null){
        $db = JFactory::getDbo();
        $productId = &JRequest::getCmd('id', 0);
        if($productId > 0)
        {
            $product = PointProvider::getProduct($db, array('pid'=>$productId));
			$nameProduct = unserialize($product->name);
			$product->name =  $nameProduct['en-GB'];
		}
        
        $this->assignRef('product', $product);
        parent::display($tpl);
    }

    function displayUpdateredemption($tpl = null)
    {
        $app = &JFactory::getApplication();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $user_id = JRequest::getInt('uid');
        $task = JRequest::getCmd('task');
        $db = JFactory::getDbo();
        
        $user = JFactory::getUser();
        $user_info = WrdHelper::getUserProfile($user_id) ;
		
        $models = PointProvider::getRedemptionByCode($db, array('code'=>strval($_GET['code'])));
		$tr = PointProvider::getTransactionByCode($db, array('code'=>strval($_GET['code'])));
		
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		if(isset($_POST) && !empty($_POST) && ( $_POST['approved'] != 9))
        {
            $arrProductId = explode(",",substr($_POST['voucher_id'],0,-1));
			$model = &JModelLegacy::getInstance('products','WrdModel');
			$updateValues = array(
                'outlet' => intval($_POST['pick_up_at']),
				'updated_by' => intval($_POST['updated_by']),
				'updated_date' => date("Y-m-d H:i:s"),
                'pick_up_date' => ($_POST['pick_up_date']),
                'status_of_redemption_date' => ($_POST['deliver_date']),
                'status' => ($_POST['status_of_redemption_date'] != '' ? 1 : 0),
                'code' => strval($_POST['codeverify']),
                'requested_outlet' => intval($_POST['requested_outlet'])
            );
			
			for($i=0;$i<count($arrProductId);$i++){
				$updateValues['id'] = $arrProductId[$i];
				$updateValues['product_id'] = $_POST["product$arrProductId[$i]"];
				$updateValues['code_voucher'] = $_POST["product_list_$arrProductId[$i]_voucher"];
				$updateValues['expired'] = $_POST["product_list_$arrProductId[$i]_date"];
				$updateValues['idrv'] = $_POST["idr$arrProductId[$i]"];
				$updateValues['idrv'] = $_POST["idr$arrProductId[$i]"];
				$model->updateRedemption($updateValues);
			}
            $app->redirect('index.php?option=com_wrd&controller=profile&layout=updateredemption&id='.(intval($_POST['redemption_user_id'])).'&uid='.$user_id.'&code='.$updateValues['code'],'Updated') ;
        }
		
        if(!empty($models)) {
            $user = PointProvider::getUserById($db, array('id'=>$models[0]->user_id));    
            
            $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx2','pick_up_at',$models[0]->pick_up_at,'','pick_up_at','','and cid = 01' );
			$lists['requested_outlet'] = JHTML::_('wrd.listOutletsEx2','requested_outlet',$models[0]->requested_outlet,'','requested_outlet','','and cid = 01' );
	
            $lists['filter_pick_up_date'] = $models[0]->pick_up_date;
            $lists['filter_deliver_date'] = $models[0]->status_of_redemption_date;
            
            $lists['filter_extra_status'] = JHTML::_('wrd.listStatusRedemptionRaw','extra_status',  $models[0]->status_of_redemption);
        }
        
        JToolBarHelper::title( JText::_( 'Redemption : <small><small>[ Update ]</small></small>','transaction.png')) ;
        WrdHelper::addSubMenu();
		
        $this->assignRef('models', $models);
		$this->assignRef('tr', $tr);
        $this->assignRef('user', $user);
        $this->assignRef('lists', $lists);
        $this->assignRef('user_info', $user_info);
        parent::display($tpl);
    }
    
    function displayPrintredemption($tpl = null)
    {
     
		$app = &JFactory::getApplication();
		$adminuser = &JFactory::getUser();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $user_id = JRequest::getInt('uid');
        $task = JRequest::getCmd('task');
        $db = JFactory::getDbo();
        $models = PointProvider::getRedemptionByCode($db, array('code'=>strval($_GET['code'])));
		$tr = PointProvider::getTransactionByCode($db, array('code'=>strval($_GET['code'])));
		if(!empty($models)) {
            $user = PointProvider::getUserById($db, array('id'=>$models[0]->user_id));    
        }
        $this->assignRef('models', $models);
		$this->assignRef('tr', $tr);
        $this->assignRef('user', $user);
		$this->assignRef('admin', $adminuser);
        parent::display($tpl);
    }
	
	function displayExredemption($tpl = null){
		
		$app = &JFactory::getApplication();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $user_id = JRequest::getInt('uid');
        $task = JRequest::getCmd('task');
        $db = JFactory::getDbo();
        $models = PointProvider::getRedemptionByCode($db, array('code'=>strval($_GET['code'])));
		$tr = PointProvider::getTransactionByCode($db, array('code'=>strval($_GET['code'])));
		if(!empty($models)) {
            $user = PointProvider::getUserById($db, array('id'=>$models[0]->user_id));    
        }

        $this->assignRef('models', $models);
		$this->assignRef('tr', $tr);
        $this->assignRef('user', $user);
        parent::display($tpl);
    }
    
    function displayAddredemption($tpl = null){
        
		$app = &JFactory::getApplication();
        $context = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $user_id = JRequest::getInt('uid');
		
		$task = JRequest::getCmd('task');
		if($task == 'savenewredemption'){
			$model = &JModelLegacy::getInstance('products','WrdModel');
            $result = $model->saveAddRedemption($_POST);
			$app->redirect('index.php?option=com_wrd&controller=profile&layout=printredemption&code='.$result['code']) ;
        }

        $filter_category         = $app->getUserStateFromRequest($context.$view.'cat_id','cat_id','','Array');
        $js_category_to_product = ' style="width:150px;" multiple="multiple" ';
        
        $lists['categories']   = JHTML::_('wrd.listProductCategoryStyleTwo','cat_id[]',$filter_category,$js_category_to_product,'cat_id',1 );
        $lists['products']     = JHTML::_('wrd.listPublishedProducts','product_id',$filter_category,' style="width:150px;" ','product_id', 1 );
		
		$filter_pick_up_outlet     = $app->getUserStateFromRequest( $context.$view.'pick_up_at','pick_up_at','','string' );
		$filter_requested_outlet   = $app->getUserStateFromRequest( $context.$view.'requested_outlet','requested_outlet','','string' );           
        
        $lists['filter_pick_up_outlet'] = JHTML::_('wrd.listOutletsEx2','pick_up_at',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        $lists['requested_outlet'] = JHTML::_('wrd.listOutletsEx2','requested_outlet',$filter_pick_up_outlet,'','pick_up_at','','and cid = 01' );
        
        $pick_up_date     = $app->getUserStateFromRequest( $context.$view.'pick_up_date','pick_up_date','','string' );              
        $lists['filter_pick_up_date'] = $pick_up_date;
        
        $deliver_date     = $app->getUserStateFromRequest( $context.$view.'deliver_date','deliver_date','','string' );              
        $lists['filter_deliver_date'] = $deliver_date;

        $fitler_status     = $app->getUserStateFromRequest( $context.$view.'extra_status','extra_status','','string' );              
        $lists['filter_extra_status'] = JHTML::_('wrd.listStatusRedemptionRaw','extra_status',  $fitler_status);
        
        $lists['allCategoriesOfAllProducts']     = JHTML::_('wrd.allProductsOfAllCategories');
        $lists['scriptCategoryProduct']     = JHTML::_('wrd.buildScriptSelectCategoryProduct');
        
		
        $user = &JFactory::getUser();
        $user_info = WrdHelper::getUserProfile($user_id);
		
		$model_outlet = &JModelLegacy::getInstance('outlets','WrdModel');
		$outlet = $model_outlet->getItem($user_info->pick_up_at);
		$p_o_u = WrdHelper::getPoints($user_info->user_id);
		
        JToolBarHelper::title( JText::_( 'Redemption : <small><small>[ New ]</small></small>','transaction.png')) ;
        WrdHelper::addSubMenu('config',$view);
		$this->sidebar = JHtmlSidebar::render();
		
        $this->assignRef('user', $user);
        $this->assignRef('user_info', $user_info);
        $this->assignRef('p_o_u', $p_o_u);
        $this->assignRef('outlet', $outlet);
        $this->assignRef('job', $user_info->o_job);
        $this->assignRef('lists', $lists);
        parent::display($tpl);
    }    
            
	function displayNew_redemption($tpl = null){
		$app = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$user_id = JRequest::getInt('uid');
		
		JToolBarHelper::title( JText::_( 'Redemption : <small><small>[ New ]</small></small>','transaction.png')) ;
 		
		WrdHelper::addSubMenu('config',$view);
		$this->sidebar = JHtmlSidebar::render();
		
		JToolBarHelper::custom('products_page','new','','Products',false);
		JToolBarHelper::save('save_new_redemption', 'Save');
		JToolBarHelper::cancel( 'redirect_to_profile', 'Cancel' );
		
		$filter_category 		= $app->getUserStateFromRequest($context.$view.'cat_id','cat_id','','int');
		$js_category_to_product = "onchange=\"changeProducts( 'product_id', sectioncategory,document.adminForm.cat_id.options[document.adminForm.cat_id.selectedIndex].value , 0, 0);\"";
		$lists['category'] 		= JHTML::_('wrd.listProductCategory','cat_id',$filter_category,$js_category_to_product,'cat_id',1 );
		$lists['products'] 		= JHTML::_('wrd.listProducts','product_id','','','product_id', 1 );
		
		$lists['cat_to_product'] 	= JHTML::_('wrd.CategoryToProduct');
		
		$user = JFactory::getUser();
		$user_info = WrdHelper::getUserProfile($user_id) ;
		if(!empty($user_info->user_id)){
			$outlet = $this->getOutletDetails($user_info->pick_up_at);
			$p_o_u = WrdHelper::getPoints($user_info->user_id);
			if($user_info->job != 'other'){
				$job = $this->getJobName($user_info->job) ;
			}else{
				$job = $user_info->o_job ;
			}
		}
		$this->assignRef('user',	$user);
		$this->assignRef('user_info',	$user_info);
		$this->assignRef('p_o_u',	$p_o_u);
		$this->assignRef('outlet',	$outlet);
		$this->assignRef('job',$job);
		$this->assignRef('lists',	$lists);
		parent::display($tpl);
	}
	
	function getRedemtion($id = 0){
		$db = JFactory::getDbo();
		$query = 'SELECT `r`.*,`u`.username AS created_by,`uu`.username AS updated_by  
		FROM #__wrd_redemption AS `r` 
			LEFT JOIN #__users AS `u` ON `r`.created_id = `u`.id
			LEFT JOIN #__users AS `uu` ON `r`.updated_by = `uu`.id
		WHERE `r`.user_id ='.$id.' ORDER BY id DESC
		';
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs;
	}
	
	function getRedemtionTotalCost($id = 0){
		$db = JFactory::getDbo();
		$query = 'SELECT sum(point) as totalcost FROM #__wrd_redemption WHERE user_id ='.$id;
		$query .= ' and ( approved = 1 || approved = 0) ' ;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs->totalcost ;
	}
	
	function getListRedemtion($id = 0,$yfrom = 0,$mfrom = 0,$dfrom = 0,$yto = 0,$mto = 0,$dto = 0){
		$db = JFactory::getDbo();
		if(empty($yfrom)){
			$yfrom = 'YEAR(exchange_date)' ;
		}
		if(empty($yto)){
			$yto = 'YEAR(exchange_date)' ;
		}
		if(empty($mfrom)){
			$mfrom = 'MONTH(exchange_date)' ;
		}
		if(empty($mto)){
			$mto = 'MONTH(exchange_date)' ;
		}
		if(empty($dfrom)){
			$dfrom = 'DAY(exchange_date)' ;
		}
		if(empty($dto)){
			$dto = 'DAY(exchange_date)' ;
		}
		$query = 'SELECT * FROM #__wrd_redemption WHERE user_id ='.$id;
		$query .= ' and exchange_date >= (concat('.$yfrom.',"-",'.$mfrom.',"-",'.$dfrom.'," ",HOUR(exchange_date),":",MINUTE(exchange_date),":",SECOND(exchange_date)))';
		$query .= ' and exchange_date <=(concat('.$yto.',"-",'.$mto.',"-",'.$dto.'," ",HOUR(exchange_date),":",MINUTE(exchange_date),":",SECOND(exchange_date)))' ;
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs;
	}
	
	function getRedemptionDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_redemption WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
	
	function getComplains($id = 0){
		$db = JFactory::getDbo();
		$query = ' 	SELECT
					c.id, 
					c.guest_name,
					c.complain_type,
					c.meal_period,
					c.complain,
					outlet.name as outlet_name,
					c.visit_date,
					c.action_taken,
					c.created_date,
					u.name as handle_name,
					c.follow_up,
					c.o_manager,
					c.vip_number
					FROM #__wrd_complain as c 
					LEFT JOIN #__users as u ON u.id = c.handle_by
					LEFT JOIN #__wrd_outlets as outlet ON ( c.o_code = outlet.code && outlet.pid != "00" )
				' ;
		$query .= ' WHERE `vip_number` = '.$id.' order by c.id desc' ;
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		return $rs ;
	}
	
	function getmservices($id = 0){
		$db = JFactory::getDbo();
		$query = ' 	SELECT
					c.id, 
					c.guest_name, 
					c.vip_number, 
					outlet.name as outlet_name, 
                    outlet.code as `transaction`,
					c.meal_period, 
					c.visit_date, 
					c.questions, 
					c.answer, 
					c.member_type, 
					c.follow_up,
					c.top_spender_date,
					c.new_join_member_date 	,
					c.inactive_member_date,
					c.daily_top_date,	
					c.created_date, 
					u.name as handle_name,
                    `p`.pick_up_date,
                    `p`.l_name,
                    `p`.f_name
                    
					FROM #__wrd_mservices as c 
					LEFT JOIN #__users as u ON u.id = c.handle_by
                    LEFT JOIN #__wrd_profile as `p` ON `p`.member_id = c.vip_number
                    
					LEFT JOIN #__wrd_outlets as outlet ON ( c.o_code = outlet.code && outlet.pid != "00" )
				' ;
		$query .= ' WHERE `vip_number` = '.$id.' order by c.id desc' ;
		$db->setQuery($query);
		$rs = $db->loadObjectList();
        
        if(!empty($rs))
        {
            $sql = "
                SELECT
                    MAX(`t`.date_receipt) AS `date_receipt`
                FROM #__wrd_transaction `t`
                WHERE `t`.vip_number IN(".$rs[0]->vip_number.")
                GROUP BY `t`.vip_number;
            ";
            $db->setQuery($sql);
            $transactions = $db->loadObject();
            $transactions = ($transactions ? $transactions->date_receipt : ''); 
            for($i=0; $i<count($rs); $i++)
            {
                $rs[$i]->transaction = $transactions; 
            }
        }
            
		return $rs ;
	}
	
	function getTransactionOutlet($transaction = 0){
		$db = &JFactory::getDbo();
		
		if($transaction ==0){
			return 0 ;
		}
		
		$query = 'SELECT outlet FROM #__wrd_transaction WHERE transaction_id ='.$transaction;
		$db->setQuery($query);
		$rs = $db->loadObject();
		
		if($rs->outlet ==0){
			return 0 ;
		}
		
		$query = 'SELECT name FROM #__wrd_outlets WHERE pid != "00" and code ='.$rs->outlet;
		$db->setQuery($query);
		$rs = $db->loadObject();
		
		return $rs->name ;
	}
	
	function getProductDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_products WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
	
	function displayRedemptions($tpl = null){
  		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$user = JFactory::getUser();
		$cid = JRequest::getInt('id');
		$rid = JRequest::getInt('rid');
		$detail = array();
		$model = $this->getModel() ;
		
		WrdHelper::addSubMenu('config',$view);
		$this->sidebar = JHtmlSidebar::render();
		
		JToolBarHelper::title(   JText::_( 'Redemption Manager' ),'job.png' );
		JToolBarHelper::save('save_sub_point','Save & Close');
		JToolBarHelper::cancel( 'cancel', 'Close' );
		
  		if($cid != 0){
			$detail	= &$model->getItem($cid);
		}
		if($rid != 0){
			$redemption_detail	= $this->getRedemptionDetails($rid);
		}
        //var_dump($redemption_detail);
		$lists = array();
		if(!empty($detail->user_id)){
			$point = $this->getPoint($detail->user_id);
		}
		
		$t_outlet = array();
		if(!empty($detail->user_id)){
			foreach ($point as $child_point){
				$t_outlet[$child_point->transaction] = $this->getTransactionOutlet($child_point->transaction) ;
			}
		}
		
		$this->assignRef('point',	$point);
		$this->assignRef('t_outlet',	$t_outlet);
		$this->assignRef('user_info',	$detail);
		$this->assignRef('redemption',	$redemption_detail);
		parent::display($tpl);
  	}
  	
	function getPointOfTran($u_id, $tran_id){
		$db = JFactory::getDbo();
		$query = 'SELECT point FROM #__wrd_point WHERE `user_id` = '.$u_id.' and `transaction` = '.$tran_id ;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs->point;	
	}
  	
  	function displayRdetails($tpl = null){
  		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		$user = JFactory::getUser();
		$id = JRequest::getInt('id');
		$model = $this->getModel() ;
		
		WrdHelper::addSubMenu('config',$view);
		$this->sidebar = JHtmlSidebar::render();
		
		JToolBarHelper::title(   JText::_( 'Redemption Details' ),'job.png' );
		JToolBarHelper::save('save_redemption_details','Save & Close');
		JToolBarHelper::cancel('redirect_to_profile', 'Cancel' );
		
  		if($id != 0){
			$redemption_detail	= $this->getRedemptionDetails($id);
		}
		
		$user_info = WrdHelper::getUserProfile($redemption_detail->user_id,'userid') ;
		$pro_info = $this->getProductDetails($redemption_detail->product_id) ;
		$outlet_info = $this->getOutletDetails($user_info->pick_up_at) ;

		$lists = array();
		$lists['pick_up_oulet'] 	= JHTML::_('wrd.listOutletsP','pick_up_at',$redemption_detail->pick_up_at, '' , 'width305' , '' , $condition = 'and pid != 00');
		$this->assignRef('redemption',	$redemption_detail);
		$this->assignRef('pro_info',	$pro_info);
		$this->assignRef('outlet_info',	$outlet_info);
		$this->assignRef('lists',	$lists);
		parent::display($tpl);
  	}
  	
	function getOutletDetails($id){
		$db = JFactory::getDbo();
		$query = 'SELECT * FROM #__wrd_outlets WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs;
	}
	
	function getJobName($id = 0){
		$db = JFactory::getDbo();
		$query = 'SELECT name FROM #__wrd_job WHERE id ='.$id;
		$db->setQuery($query);
		$rs = $db->loadObject();
		return $rs->name;
	}
	
	function getTransaction($id = 0,$yfrom = 0,$mfrom = 0,$dfrom = 0,$yto = 0,$mto = 0,$dto = 0,$total = 0){
		$db = JFactory::getDbo();
		//condition by Birth Day	
		if(empty($yfrom)){
			$yfrom = 'YEAR(a.date_receipt)' ;
		}
		if(empty($yto)){
			$yto = 'YEAR(a.date_receipt)' ;
		}
		if(empty($mfrom)){
			$mfrom = 'MONTH(a.date_receipt)' ;
		}
		if(empty($mto)){
			$mto = 'MONTH(a.date_receipt)' ;
		}
		if(empty($dfrom)){
			$dfrom = 'DAY(a.date_receipt)' ;
		}
		if(empty($dto)){
			$dto = 'DAY(a.date_receipt)' ;
		}
		if($total == 0){
			$query = '
				SELECT a.*, b.name as outletname
				FROM #__wrd_transaction as a 
				LEFT JOIN #__wrd_outlets as b ON a.outlet = b.code
				WHERE a.vip_number ='.$id.' and b.pid != 00 
			';
			$query .= ' and a.date_receipt >= (concat('.$yfrom.',"-",'.$mfrom.',"-",'.$dfrom.'," ",HOUR(a.date_receipt),":",MINUTE(a.date_receipt),":",SECOND(a.date_receipt)))';
			$query .= ' and a.date_receipt <=(concat('.$yto.',"-",'.$mto.',"-",'.$dto.'," ",HOUR(a.date_receipt),":",MINUTE(a.date_receipt),":",SECOND(a.date_receipt)))' ;
			$query .= ' order by `date_receipt` DESC limit 0, 20 ';
			$db->setQuery($query);
			$rs = $db->loadObjectList();
		}else{
			//totalcosttran
			$query = '
				SELECT sum(total) as totalcosttran
				FROM #__wrd_transaction as a
				WHERE a.vip_number ='.$id ;
			$db->setQuery($query);
			$rs = $db->loadObject();
		}
		return $rs;
		
	}
	
	function getLuckyNum($condition = '',$total=0,$limitstart=0){
		$db = JFactory::getDbo();
		if($total==0){
			$query = 'SELECT id AS value, number AS text FROM #__wrd_lucky_num';
			$query .= ' WHERE published = 1 and available = 1 ';
			if(!empty($condition)){
				$query .= ''.$condition.''; 
			}
			$query .= 'ORDER BY number ASC LIMIT '.$limitstart.',20' ;
			$db->setQuery( $query );
			return $db->loadObjectList() ;
		}else{
			$query = 'SELECT count(id) AS total_lnum FROM #__wrd_lucky_num';  
			$query .= ' WHERE published = 1 and available = 1 ';
			if(!empty($condition)){
				$query .= ''.$condition.' LIMIT '.$limitstart.',20'  ; 
			}
			$db->setQuery( $query );
			return $db->loadObject() ;
		}
  	}
}
?>
